package com.itheima.service.imp;

import com.itheima.DTO.SubmitOrder;
import com.itheima.mapper.OrderMapper;
import com.itheima.pojo.OderAndMember;
import com.itheima.pojo.Order;
import com.itheima.pojo.OrderSetting;
import com.itheima.service.OrderService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigInteger;
import java.time.LocalDate;
import java.time.ZoneId;
import java.time.format.DateTimeFormatter;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

@Service
@Slf4j
public class OrderServiceImp implements OrderService {

    @Autowired
    private OrderMapper orderMapper;
    @Autowired
    private RedisTemplate redisTemplate;

    public OderAndMember findOrderAndMemberById(Integer id) {
        return orderMapper.findOrderAndMemberById(id);
    }


    @Transactional
    public String submitOrder(SubmitOrder submitOrder){
        log.info("提交预约：{}", submitOrder);
        Integer memberId = orderMapper.getMember(submitOrder.getIdCard());
        //1.判断当前用户是否为会员，如果是会员，直接预约，如果不是会员，自动注册，再预约
        if (memberId == null || memberId == 0) {
            Map<String, Object> params = new HashMap<>();
            params.put("name", submitOrder.getName());
            params.put("sex", submitOrder.getSex());
            params.put("idCard", submitOrder.getIdCard());
            params.put("telephone", submitOrder.getTelephone());
            params.put("date", LocalDate.now());
            params.put("memberId", null);
            orderMapper.addMember(params);

            // 确保 memberId 是 BigInteger 类型并进行转换
            Object memberIdObj = params.get("memberId");
            if (memberIdObj instanceof BigInteger) {
                memberId = ((BigInteger) memberIdObj).intValue();
            } else if (memberIdObj instanceof Integer) {
                memberId = (Integer) memberIdObj;
            } else if (memberIdObj instanceof Long) {
                memberId = ((Long) memberIdObj).intValue();
            } else {
                throw new RuntimeException("Unexpected type for memberId: " + memberIdObj.getClass().getName());
            }
        }
        log.info("会员id：{}",memberId);

        //2.效验验证码
        String code = (String)redisTemplate.opsForValue().get(submitOrder.getTelephone());
        if (code == null || !code.equals(submitOrder.getValidateCode())) {
//            return  "验证码错误";
            throw new RuntimeException("验证码错误");
        }
//        预约日期的预约人数没有设置的话不能预约。
//        预约日期是否已经约满，如果已经约满则无法预约。
//        不能重复预约（同一个用户在同一天预约了同一个套餐）。
        //3.查询t_ordersetting表，判断是否预约满了 判断可预约人数是否没有设置可预约人数
        OrderSetting orderSetting = orderMapper.findOrderSettingByDate(submitOrder.getOrderDate());
        if (orderSetting == null){
//            return "预约日期的预约人数没有设置的话不能预约。";
            throw new RuntimeException("预约日期的预约人数没有设置的话不能预约");
        }
        if (orderSetting.getNumber() == 0){
//            return "预约日期的预约人数没有设置的话不能预约。";
            throw new RuntimeException("预约日期的预约人数没有设置的话不能预约");
        }
        if (orderSetting.getNumber() <= orderSetting.getReservations()){
//            return "预约日期是否已经约满，如果已经约满则无法预约。";
            throw new RuntimeException("预约日期是否已经约满，如果已经约满则无法预约。");
        }

        //4.判断当前用户是否已经预约过，如果已经预约过，则不能重复预约。
        Order order = orderMapper.findOrderByMemberIdAndDate(memberId, submitOrder.getOrderDate(), submitOrder.getSetmealId());
        if (order != null){
//            return "不能重复预约（同一个用户在同一天预约了同一个套餐）。";
            throw new RuntimeException("不能重复预约（同一个用户在同一天预约了同一个套餐）。");
        }
        //一切检查判断合规之后，插入数据
        // 创建一个新的 Order 实例并设置属性
        Order orderPojo = new Order();

        // 将 String 类型的日期转换为 LocalDate 类型
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd");
        LocalDate orderDate = LocalDate.parse(submitOrder.getOrderDate(), formatter);
        // 将 LocalDate 类型转换为 Date 类型
        Date date = Date.from(orderDate.atStartOfDay(ZoneId.systemDefault()).toInstant());
        orderPojo.setOrderDate(date);
        orderPojo.setSetmealId(submitOrder.getSetmealId());
        orderPojo.setMemberId(memberId);
        orderPojo.setOrderType("微信预约");
        orderPojo.setOrderStatus("未到诊");
        orderMapper.addOrder(orderPojo);

        return orderPojo.getId().toString();

    }
}
